package com.example.myplayer

import android.content.res.Configuration
import android.os.Bundle
import android.view.Gravity
import android.view.SurfaceHolder
import android.view.View
import android.widget.FrameLayout
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.controller_layout.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private lateinit var playViewModel: PlayViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //更新视频播放的进度条
        updatePlayProgress()
        //获得playViewModel实例
        playViewModel = ViewModelProvider(this).get(PlayViewModel::class.java).apply {

            //转动缓冲条观察
            progerssBarVisibility.observe(this@MainActivity, Observer {
                progressBar.visibility = it
            })
            //分辨率观察
            videowResolution.observe(this@MainActivity, Observer {
                // 获得视频的最大值
                seekBar.max = mediaPlayer.duration

                //不能直接调用resizePlayer(it.first,it.second)
                //把他放在消息队列中，等layout加载完成后才调用resizePlayer
                playFrame.post {
                    resizePlayer(it.first, it.second)
                }
            })

            //视频控制条观察
            controllerFrameVisibility.observe(this@MainActivity, Observer {
                controllerFrame.visibility = it

            })

            //视频缓冲进度百分比观察
            bufferPercent.observe(this@MainActivity, Observer {
                seekBar.secondaryProgress = seekBar.max * it / 100
            })

            //视频播放状态观察
            playStatus.observe(this@MainActivity, Observer {
                controlerButton.isClickable = true
                when (it) {
                    PlayStatus.Paused -> controlerButton.setImageResource(R.drawable.ic_baseline_play_arrow_24)
                    PlayStatus.Completed -> controlerButton.setImageResource(R.drawable.ic_baseline_replay_24)
                    PlayStatus.NoReady -> controlerButton.isClickable = false
                    else -> controlerButton.setImageResource(R.drawable.ic_baseline_pause_24)
                }
            })

        }

        //添加生命周期的观察
        lifecycle.addObserver(playViewModel.mediaPlayer)

        //视频播放键监听
        controlerButton.setOnClickListener {
            playViewModel.togglePlayerStatus()
        }

        //监听视频中的控制条
        playFrame.setOnClickListener { playViewModel.toggleControllerVisibility() }

        //拖动视频进度条监听
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progerss: Int, fromUser: Boolean) {
                //如果用户拖动视频进度条
                if (fromUser) {
                    //调用拖动视频播放进度条
                    playViewModel.playSeekToProgress(progerss)
                }

            }

            override fun onStartTrackingTouch(p0: SeekBar?) {
                //TODO("Not yet implemented")
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
                //TODO("Not yet implemented")
            }

        })

        surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceChanged(
                p0: SurfaceHolder, p1: Int, p2: Int, p3: Int
            ) {
                playViewModel.mediaPlayer.setDisplay(p0)
                //播放视频时防止屏幕锁定，播放的时候屏幕永远点亮
                playViewModel.mediaPlayer.setScreenOnWhilePlaying(true)

            }

            override fun surfaceDestroyed(p0: SurfaceHolder) {
                //TODO("Not yet implemented")
            }

            override fun surfaceCreated(p0: SurfaceHolder) {
                //TODO("Not yet implemented")
            }

        })
    }

    //当横屏时调用hideSystemUI()
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            hideSystemUI()
            //重新获取宽高比
            playViewModel.emitVideoResolution()
        }
    }

    private fun resizePlayer(width: Int, height: Int) {
        if (width == 0 || height == 0) return
        surfaceView.layoutParams = FrameLayout.LayoutParams(
            playFrame.height * width / height,
            FrameLayout.LayoutParams.MATCH_PARENT,
            Gravity.CENTER
        )
    }

    //更新视频播放的进度条
    private fun updatePlayProgress() {
        //协程，不能柱塞主线程
        lifecycleScope.launch {
            while (true) {
                delay(500)
                seekBar.progress = playViewModel.mediaPlayer.currentPosition
            }

        }

    }


    //横屏时全屏（隐藏标题栏）
    //View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY,全屏时点击显示控制条
    private fun hideSystemUI() {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                // Set the content to appear under the system bars so that the
                // content doesn't resize when the system bars hide and show.
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                // Hide the nav bar and status bar
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
    }
}